package main

import (
	"context"
	"encoding/json"
	"google.golang.org/grpc"
	"google.golang.org/grpc/credentials/insecure"
	"log"
	pb "productinfo/service/service"
	"time"
)

const (
	address = "localhost:50051"
)

func main() {
	// Set up a connection to the product-server.
	conn, err := grpc.Dial(address, grpc.WithTransportCredentials(insecure.NewCredentials()))
	if err != nil {
		log.Fatalf("did not connect: %v", err)
	}
	defer func(conn *grpc.ClientConn) {
		log.Println("close connection")
		err := conn.Close()
		if err != nil {
			log.Fatalf("Failed to close connection: %v", err)
			return
		}
	}(conn)
	c := pb.NewProductInfoClient(conn)

	// Contact the product-server and print out its response.
	name := "Apple iPhone 11"
	description := "Meet Apple iPhone 11. All-new dual-camera system with Ultra Wide and Night mode."
	price := float32(699.00)
	ctx, cancel := context.WithTimeout(context.Background(), time.Second)
	defer cancel()
	r, err := c.AddProduct(ctx, &pb.Product{Name: name, Description: description, Price: price})
	if err != nil {
		log.Fatalf("Could not add product: %v", err)
	}
	log.Printf("Product ID: %s added successfully\r\n", r.Value)
	product, err := c.GetProduct(ctx, &pb.ProductID{Value: r.Value})
	if err != nil {
		log.Fatalf("Could not get product: %v", err)
	}
	marshal, _ := json.MarshalIndent(product, "", " ")
	log.Printf("Product: %s \r\n", string(marshal))
}
